package com.tcm.day07;

import com.tcm.day06.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 二叉树层序遍历
 * https://leetcode.cn/problems/binary-tree-level-order-traversal/description/?envType=problem-list-v2&envId=binary-tree
 */
public class Code01_TreeLevelTraversal {

    public List<List<Integer>> levelOrder(TreeNode root) {

        List<List<Integer>> result = new ArrayList<>();
        if (null == root) return result;

        Queue<TreeNode> queue = new LinkedList();
        queue.add(root);

        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> curAns = new ArrayList<>();

            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                curAns.add(node.val);

                if (null != node.left) {
                    queue.add(node.left);
                }

                if (null != node.right) {
                    queue.add(node.right);
                }
            }
            result.add(curAns);
        }

        return result;
    }

}
